﻿using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace FBS.Framework
{
    public class Serializer
    {
        /// <summary>
        /// To convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String.
        /// </summary>
        /// <param name="characters">Unicode Byte Array to be converted to String</param>
        /// <returns>String converted from Unicode Byte Array</returns>
        private static string UTF8ByteArrayToString(byte[] characters)
        {
            UTF8Encoding encoding = new UTF8Encoding();

            string constructedString = encoding.GetString(characters);

            return constructedString;
        }

        public static string SerializeObject1(Object pObject)
        {
            try
            {
                string XmlizedString = null;

                MemoryStream memoryStream = new MemoryStream();
                memoryStream.Position = 0;

                XmlSerializer xs = new XmlSerializer(pObject.GetType());

                XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

                xs.Serialize(xmlTextWriter, pObject);

                memoryStream = (MemoryStream)xmlTextWriter.BaseStream;

                XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());

                return XmlizedString;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        /// <summary>
        /// Serialize an object into an XML string
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public static string SerializeObject<T>(T obj)
        {
            try
            {
                string xmlString = null;
                var memoryStream = SerializeObjectToStream(obj);

                xmlString = UTF8ByteArrayToString(memoryStream.ToArray());

                xmlString = xmlString.Replace("<?xml version=\"1.0\"?>", "<?xml version=\"1.0\" encoding=\"utf-8\"?>");

                return xmlString;
            }
            catch
            {
                return string.Empty;
            }
        }

        public static MemoryStream SerializeObjectToStream<T>(T obj)
        {
            var xs = new XmlSerializer(obj.GetType());
            var stream = new MemoryStream();

            xs.Serialize(stream, obj);
            stream.Position = 0;

            return stream;
        }
    }
}
